package serv_impl

import (
	"context"
	"fmt"
	"time"

	"atomgit.com/openlinksaas/proto-gen-go.git/project_member_api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func getTokenInfo(addr, token string) (*project_member_api.OneTimeTokenInfo, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	conn, err := grpc.DialContext(ctx, addr, grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithInitialConnWindowSize(1<<30), grpc.WithInitialWindowSize(1<<30))
	if err != nil {
		return nil, err
	}

	defer conn.Close()

	client := project_member_api.NewProjectMemberApiClient(conn)
	res, err := client.GetOneTimeToken(ctx, &project_member_api.GetOneTimeTokenRequest{
		Token: token,
	})
	if err != nil {
		return nil, err
	}
	if res.Code != project_member_api.GetOneTimeTokenResponse_CODE_OK {
		return nil, fmt.Errorf(res.ErrMsg)
	}
	return res.TokenInfo, nil
}

func getK8sClientSet(kubConfigFile string) (*kubernetes.Clientset, error) {
	cfg, err := clientcmd.BuildConfigFromFlags("", kubConfigFile)
	if err != nil {
		return nil, err
	}
	return kubernetes.NewForConfig(cfg)
}
